package hihocoder;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;

/**
 * 
 */

/**
 * @author zhongfang
 *
 */
public class 逃离迷宫II {

	static int[][] dirs={{-1,0},{1,0},{0,1},{0,-1}};
	static class Pos implements Comparable<Pos>{
		public Pos(int k, int l, int i2, int m) {
			this.i=k;
			this.j=l;
			this.curDir=i2;
			this.changeTimes=0;
		}
		/**
		 * 位置
		 */
		int i,j;
		/**
		 * 当前方向
		 */
		int curDir;
		/**
		 * 改变方向的次数
		 */
		int changeTimes;
		@Override
		public int compareTo(Pos o) {
			return this.changeTimes-o.changeTimes;
		}
		
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner scanner=new Scanner(System.in);
		int N=scanner.nextInt();
		int M=scanner.nextInt();
		scanner.nextLine();
		char[][] mi=new char[N][M];
		int[] startPos=new int[2];
		for (int i = 0; i < N; i++) {
			String string=scanner.nextLine();
			for (int j = 0; j < M; j++) {
				mi[i][j]=string.charAt(j);
				if(mi[i][j]=='S'){
					startPos[0]=i;
					startPos[1]=j;
				}
			}
		}
		System.out.println(getResult(mi,startPos));
	}
	private static int getResult(char[][] mi, int[] startPos) {
		int minChanges=-1;
		int n=mi.length;
		int m=mi[0].length;
		PriorityQueue<Pos> queue=new PriorityQueue<>();
		for (int i = 0; i < 4; i++) {
			Pos curPos=new Pos(startPos[0],startPos[1],i,0);
			queue.add(curPos);
		}
		while (!queue.isEmpty()) {
			Pos oldPos=queue.poll();
			Pos newPos=new Pos(oldPos.i+dirs[oldPos.curDir][0], oldPos.j+dirs[oldPos.curDir][1], oldPos.curDir, oldPos.changeTimes);
			if(isBound(newPos, mi.length, mi[0].length)||mi[newPos.i][newPos.j]=='#'){
				for (int i = 0; i < 4; i++) {
					if(i==oldPos.curDir){
						continue;
					}
					int newDir=i;
					newPos=new Pos(oldPos.i+dirs[newDir][0], oldPos.j+dirs[newDir][1],newDir,oldPos.changeTimes+1);
					if(!isBound(newPos, n, m)&&mi[newPos.i][newPos.j]!='#'){
						queue.add(newPos);
						if(mi[newPos.i][newPos.j]=='T'){
							if(minChanges==-1||minChanges>newPos.changeTimes){
								minChanges=newPos.changeTimes;
							}
						}
					}
				}
			}else {//不改变方向
				queue.add(newPos);
			}
		}
		return minChanges;
	}
	private static boolean isBound(Pos newPos,int n,int m) {
		return newPos.i<0||newPos.i>=n||newPos.j<0||newPos.j>=m;
	}

}
